package com.uchonor.api.core.service;

import com.uchonor.api.core.entity.InterfaceConfig;
import com.uchonor.api.core.entity.InterfaceParameterConfig;
import com.uchonor.api.core.mapper.InterfaceConfigMapper;
import com.uchonor.olight.agent.annotation.Inject;
import com.uchonor.olight.agent.annotation.Service;
import com.uchonor.olight.agent.annotation.db.DBTransactional;
import com.uchonor.olight.agent.module.db.BaseServiceImpl;
import com.uchonor.olight.agent.utils.AssertUtils;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class InterfaceConfigService extends BaseServiceImpl<InterfaceConfigMapper, InterfaceConfig> {
    @Inject
    private ResourceService resourceService;
    @Inject
    private List<LowCodeApi> lowCodeApiList;
    @Inject
    private InterfaceParameterConfigService interfaceParameterConfigService;

    public LowCodeApi getLowCodeApiByInterfaceType(String interfaceType){
        return lowCodeApiList.stream().filter(it -> it.isSupper(interfaceType)).findFirst().orElse(null);
    }

    /**
     * 接口生效
     * @param interfaceId
     */
    @DBTransactional
    public void effectiveInterfaceConfig(String interfaceId) throws TemplateException, IOException {
        Map<String,Object> dataMap = new HashMap<>();
        // 查询接口对应的信息
        InterfaceConfig interfaceConfig = this.getById(interfaceId);
        if("1".equals(interfaceConfig.getInterfaceStatus())){
            throw new RuntimeException("接口已生效，请勿重复生效");
        }
        AssertUtils.notNull(interfaceConfig,"接口不存在!");
        LowCodeApi lowCodeApi = getLowCodeApiByInterfaceType(interfaceConfig.getInterfaceType());
        AssertUtils.notNull(lowCodeApi,"对应的接口实现不存在!");
        List<InterfaceParameterConfig> requestParamList = interfaceParameterConfigService.getListByInterfaceId(interfaceId);
        dataMap.put("interfaceConfig",interfaceConfig);
        dataMap.put("interfaceParameterConfig",requestParamList);
        lowCodeApi.doGenerate(dataMap);
    }

    @DBTransactional
    public void invalidInterfaceConfig(String interfaceId){
        // 查询接口对应的信息
        InterfaceConfig interfaceConfig = this.getById(interfaceId);
        if("0".equals(interfaceConfig.getInterfaceStatus())){
            throw new RuntimeException("接口已失效，请勿重复生效");
        }
        interfaceConfig.setInterfaceStatus("0");
        this.saveOrUpdate(interfaceConfig);
        resourceService.delete(interfaceId);
    }
}
